<template>
  <div class="disClassBox">
    <div class="btnBox height36">
      <el-button type="primary" @click="addChildClass">新增子分类</el-button>
    </div>
    <div class="content">
      <div class="leftTree setScrollbar">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <span class="span-ellipsis" slot-scope="{ node }">
            <span :title="node.label">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
      <div class="cntTab setScrollbar">
        <template>
          <el-table v-loading="loading" :data="tableData" stripe style="width: 100%">
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="classificationName" label="分类名称" width="280" show-overflow-tooltip/>
            <el-table-column prop="pname" label="上级分类">
            </el-table-column>
            <el-table-column align="center" label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  class="MR18 bg5584FF"
                  type="primary"
                  @click="editDis(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="scope.row.cateCode != 'forum' && scope.row.cateCode != 'process'"
                  size="mini"
                  class="MR18 bg5584FF"
                  type="primary"
                  @click="deleteClass(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="pageBox">
          <el-pagination
            background
            :current-page.sync="currentPage"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 编辑分类 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="editRules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input45"
      >
        <el-form-item label="分类名称" prop="classificationName">
          <el-input
            v-model.trim="ruleForm.classificationName"
            @input="change($event)"
            placeholder="请输入"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="上级分类" prop="pid">
          <el-input
            v-model.trim="ruleForm.pname"
            disabled
          />
        </el-form-item>
        <el-form-item style="width:100%">
          <div class="formBtnBox">
            <el-button type="primary" @click="updateDis('ruleForm')">提交</el-button>
            <el-button @click="editDialogVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增子分类 -->
    <el-dialog
      title="新增子分类"
      :visible.sync="addDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input45"
      >
        <el-form-item label="分类名称" prop="classificationName">
          <el-input
            v-model.trim="ruleForm.classificationName"
            @input="change($event)"
            placeholder="请输入"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="ruleForm.pid" placeholder="请选择">
            <el-option
              v-for="item in classificationData"
              :key="item.classificationId"
              :label="item.classificationName"
              :value="item.classificationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width:100%">
          <div class="formBtnBox">
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="addDialogVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除分类"
      :visible.sync="delDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要删除该分类？此操作不可逆</p>
      <div class="formBtnBox">
        <el-button type="primary" @click="sureDelete">确定</el-button>
        <el-button @click="delDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { clearTreeData } from "@/utils";
import { Message } from "element-ui";
export default {
  props: {
    currPid: {
      type: String,
      default: "0"
    },
    type: {
      type: String,
      default: "forum"
    }
  },
  data() {
    return {
      addDialogVisible: false,
      delDialogVisible: false,
      editDialogVisible: false,
      addLoading: false,
      loading: false,
      currentPage: 1,
      classificationId: null,
      total: 0,
      current: 1,
      ruleForm: {
        classificationType: 1
      },
      rules: {
        classificationName: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ],
        pid: [{ required: true, message: "请选择上级分类", trigger: "change" }]
      },
      editRules: {
        classificationName: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      treeData: [],
      classificationData: [],
      tableData: [],
      searchObj: {
        cateCode: this.type
      },
      currType: "dis", // dis:讨论分类    pro: 问题分类
      levelClass: this.type, // 下拉参数
      cateCode: this.type,
      defaultProps: {
        children: "childs",
        label: "classificationName"
      }
    };
  },
  watch: {
    currPid() {
      this.$nextTick(() => {
        this.searchObj.cateCode = this.type;
        this.init();
      });
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getTreeList();
      this.getTabdata(this.searchObj, { current: 1, limit: 10 });
      this.getClassification();
    },
    getTabdata(searchObj, pageObj) {
      this.loading = true;
      const pms = Object.assign(searchObj, pageObj);
      this.$axios
        .get("/classification/list", { params: pms })
        .then(res => {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getTreeList() {
      this.$axios
        .get("/classification/treeList", {
          params: {
            pid: this.currPid
          }
        })
        .then(res => {
          this.treeData = clearTreeData(res.data);
          // console.log("this.treeData:", this.treeData);
        })
        .catch(() => {});
    },
    getClassification() {
      this.$axios
        .get(`/classification/levelClass?cateCode=${this.levelClass}`)
        .then(res => {
          this.$nextTick(() => {
            this.classificationData = res.data;
          });
        });
    },
    handleNodeClick(data) {
      this.cateCode = data.cateCode;
      this.$set(this.searchObj, "cateCode", data.cateCode);
      this.getTabdata(this.searchObj, { current: this.current, limit: 10 });
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getTabdata(this.searchObj, { current: this.current, limit: 10 });
    },
    addChildClass() {
      this.addDialogVisible = true;
    },
    updateDis(formName){
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addLoading = true;
          this.COM.jsonsqlForUpdate({
            'sys_classification':{
              'classification_name': this.ruleForm.classificationName,
              '@where':{
                'classification_id@eq': this.ruleForm.classificationId
              }
            }
          }).then(() =>{
            this.getTreeList();
            this.getClassification();
            this.getTabdata(this.searchObj, { current: 1, limit: 10 });
            this.addLoading = false;
            this.editDialogVisible = false;
            Message.success("修改成功");
          }).catch(() =>{
            this.addLoading = false;
            Message.error("新增失败，请检查网络");
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      })
    },
    submitForm(formName) {
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert("submit!");
          this.addLoading = true;
          this.$axios
            .post("/classification/add", this.ruleForm)
            .then(() => {
              this.getTabdata(this.searchObj, {
                current: this.current,
                limit: 10
              });
              this.getTreeList();
              this.addLoading = false;
              this.addDialogVisible = false;
              Message.success("新增成功");
              this.getClassification();
            })
            .catch(() => {
              this.addLoading = false;
              Message.error("新增失败，请检查网络");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deleteClass(row) {
      console.log(row);
      let info = '', queryParams = {}
      if (this.levelClass == "forum") {
        info = '讨论'
        queryParams = {
          "sys_classification_relation:data[]": {
            "@column": "*",
            "@where": {
              "classification_id@eq": row.cateCode
            }
          }
        };
      }
      if (this.levelClass == "process") {
        info = '问题'
        queryParams = {
          "c_process:data[]": {
            "@column": "*",
            "@where": {
              "cat_code@eq": row.cateCode
            }
          }
        };
      }

      this.COM.jsonsqlForSelect(queryParams).then(res => {
        if (res.data.length > 0) {
          Message.warning(`当前分类存在绑定${info}，不能删除`);
        } else {
          this.classificationId = row.classificationId;
          this.delDialogVisible = true;
        }
      });
    },
    sureDelete() {
      console.log(this.cateCode, "cateCode");
      this.$axios
        .get(`/classification/remove?classificationId=${this.classificationId}`)
        .then(() => {
          this.delDialogVisible = false;
          this.getTreeList();
          this.getTabdata(this.searchObj, { current: this.current, limit: 10 });
          Message.success("已删除");
          this.getClassification();
        })
        .catch(() => {
          Message.error("删除失败，请检查网络");
        });
    },
    addHandleClose() {
      this.$refs.ruleForm.resetFields();
    },
    change(e) {
      this.$forceUpdate();
    },
    editDis(row){
      this.ruleForm = {
        classificationName:row.classificationName,
        classificationId:row.classificationId,
        pname:row.pname,
      }
      this.editDialogVisible = true
    }
  }
};
</script>
<style lang="scss" scoped>
.disClassBox {
  height: 100%;
  .height36 {
    height: 36px;
  }
}
.input45 {
  .el-input {
    width: 45%;
  }
  .el-select {
    width: 45%;
  }
}
</style>
